package com.shawn.baseappbygroovydsl.utils

import java.util.Calendar
import java.util.concurrent.TimeUnit
import kotlin.math.abs

object UtilTime {
    /**
     * 计算两个时间戳的差值，单位是天，以日期为天数差
     * */
    fun calculateDaysBetweenDates(timestamp1: Long, timestamp2: Long): Int {
        val calendar1 = Calendar.getInstance()
        calendar1.timeInMillis = timestamp1
        calendar1[Calendar.HOUR_OF_DAY] = 0
        calendar1[Calendar.MINUTE] = 0
        calendar1[Calendar.SECOND] = 0
        calendar1[Calendar.MILLISECOND] = 0

        val calendar2 = Calendar.getInstance()
        calendar2.timeInMillis = timestamp2
        calendar2[Calendar.HOUR_OF_DAY] = 0
        calendar2[Calendar.MINUTE] = 0
        calendar2[Calendar.SECOND] = 0
        calendar2[Calendar.MILLISECOND] = 0

        return ((calendar2.timeInMillis - calendar1.timeInMillis) / (1000 * 60 * 60 * 24)).toInt()
    }

    fun calculateAbsoluteDaysBetweenAbs(timestamp1: Long, timestamp2: Long): Long {
        val millisDiff = abs(timestamp2 - timestamp1)
        return millisDiff / (1000 * 60 * 60 * 24)
    }

    fun calculateDayDifferenceV2(timestamp1: Long, timestamp2: Long): Long {
        // 计算时间差（以毫秒为单位）
        val diffInMillis = timestamp2 - timestamp1

        // 计算差的天数，只要过了24小时就算差1天
        val daysDifference = TimeUnit.MILLISECONDS.toDays(diffInMillis) + if (diffInMillis % TimeUnit.DAYS.toMillis(1) > 0) 1 else 0

        return daysDifference
    }
}